<template>
  <PageContainer v-model:enter-options="enterOptions">
    <view class="container">
      <Header
        :is-box-shadow="false"
        :z-index="headerZindex"
        :is-go-back="!isTabbarPage"
        transparent="always"
        :isBoxHeight="true"
      >
        <template #customTitle>
          <view
            class="w-full disFlxAC justify-between"
            :style="{
              height: 'inherit',
              width:'100%',
            }"
          >
            <text class="fz-18">供需广场</text>
            <view
              class="h-32 disFlxAC px-8 fz-12 br-20 mr-9 gap-4"
              style="background-color: rgba(255, 255, 255, 0.8); color: black"
              @click="showSharePopup = true"
            >
              <text class="ali-icon">&#xe6da;</text>
              <text>分享</text>
            </view>
          </view>
        </template>
      </Header>

      <view
        class="banner"
        style="position: fixed; top: 0; background-color: #fff"
        :style="{ zIndex: headerZindex - 10 }"
      >
        <TImage
          width="750rpx"
          height="440rpx"
          src="https://hb-saas.obs.cn-south-1.myhuaweicloud.com/mall/saas/boBgImage.png"
        ></TImage>
        <view class="h-8"></view>
        <view class="bg-white py-12">
          <view style="padding: 16rpx 32rpx; height: 72rpx">
            <TSearch placeholder="请输入搜索内容" @confirm="searchFnc" />
          </view>
        </view>
      </view>
      <view :style="{ height: viewHeight }"></view>
      <YFilter
        :header-height="yFilterTop"
        :z-index="700"
        @submit="handleFilterControlChange"
      ></YFilter>

      <Paglist
        v-model="dataList"
        :is-init-api="true"
        :parame="params"
        @register="register"
        :scroll-top-bottom="220"
        :is-show-loadmore="dataList.length > 1"
      >
        <view class="pa-16">
          <template v-for="v in dataList" :key="v.id">
            <DataItem :data="v" />
          </template>
        </view>
      </Paglist>

      <view class="add-topic disFlxCC" @click.stop="handleCreate()">
        <text class="ali-icon mb-4">&#xe61f;</text>
        <text>发布</text>
      </view>
    </view>
  </PageContainer>

  <CustomShare
    v-if="enterOptions && enterOptions?.scene !== SceneValuesEnum.TIMELINE_SINGLEPAGE"
    v-model:visible="showSharePopup"
    :z-index="999"
    @register="handleCustomShareRegister"
  />
</template>

<script lang="ts" setup>
  /* supplyDemandSquare 供需广场 */
  import Header from '@/components/Header/index.vue';
  import PageContainer from '@/components/PageContainer/index.vue';
  import TSearch from '@/components/TSearch/index.vue';

  import Paglist from '@/components/Paglist/index.vue';
  import { useConList } from '@/components/Paglist/useConList';
  import { computed, provide, reactive, ref } from 'vue';
  import DataItem from '@/components/SupplyDemandSquareMain/components/DataItem.vue';
  import { onPageScroll, onShareAppMessage, onShareTimeline, onShow } from '@dcloudio/uni-app';
  import { getUrl, navigateTo, onLoad } from '@/router';
  import { supplyDemandSquareList } from '@/api/businessOpportunities';
  import type {
    ISupplyDemandSquareData,
    ISupplyDemandSquareResult,
  } from '@/api/businessOpportunities/type';
  import { AssTypeEnum } from '@/enums/orderEnum';
  import { BoTypeEnum, ReleaseTypeEnum } from '@/enums/businessOpportunitiesEnum';
  import { SceneValuesEnum } from '@/enums/sceneValuesEnum';
  import { useAppShare } from '@/hooks/core/useAppShare';
  import CustomShare from '@/components/CustomShare/index.vue';
  import { useCustomShare } from '@/components/CustomShare/hooks/useCustomShare';
  import type { CustomNavigateToOptions } from '@/router/types/nav';
  import { addAppShareLog, getTypePublicity } from '@/api';
  import { BusinessFunctionTypeEnum } from '@/enums/publicModuleEnum';
  import YFilter from '@/components/SupplyDemandSquareMain/components/YFilter.vue';
  import TImage from '@/components/TImage/index.vue';
  import { propTypes } from '@/utils/propTypes';
  import { useAppStore } from '@/store/modules/app';
  import { DynamicTabbarPagesEnum } from '@/enums/pageEnum';
  import type { PagesType } from '@/router/types/pages';

  const props = defineProps({
    isTabbarPage: propTypes.bool.def(false),
  });

  const headerZindex = ref(900);
  const enterOptions = ref<UniApp.GetLaunchOptionsSyncOptions>();
  const { tabbarList } = useAppStore();

  const bannerHeight = 440;
  const filterHeight = 87;
  const searchHeight = 152;

  const viewHeight = ref(bannerHeight + searchHeight + 'rpx');
  const yFilterTop = ref(uni.upx2px(bannerHeight + filterHeight + searchHeight));

  const { setWxSharePath, createShareQuery, setWxShareTimelineQuery } = useAppShare();
  const showSharePopup = ref(false);
  const [
    customShareRegister,
    { setWxShareOptions, setShareLogId, setShareTimelineContent, setInternalLinkOptions },
  ] = useCustomShare({
    buttons: {
      share: true,
      poster: false,
      timeline: true,
      copyLink: true,
      insertOffiaccount: true,
      offiaccount: true,
      downloadMiniprogramCode: true,
    },
  });

  /** 设置分享参数 */
  async function handleCustomShareRegister(e: any) {
    customShareRegister(e);
    const item = tabbarList.find((v) => v.component === DynamicTabbarPagesEnum.SUPPLYDEMANDSQUARE);

    let query: any = {
      name: 'supplyDemandSquare',
      options: {},
    };

    if (props.isTabbarPage && item) {
      query = {
        name: item.pagePath as PagesType,
        options: {
          component: DynamicTabbarPagesEnum.SUPPLYDEMANDSQUARE,
        },
      };
    }

    setInternalLinkOptions(query);
    const path = setWxSharePath(query);

    const routeQuery = createShareQuery(query.options);
    setWxShareOptions([
      {
        title: '资源汇聚，共创价值！',
        imageUrl: 'https://hb-saas.obs.cn-south-1.myhuaweicloud.com/mall/saas/gx_bg.png',
        path,
      },
    ]);
    const { id: shareLogId } = await addAppShareLog({
      path: getUrl(query.name),
      query: JSON.stringify(routeQuery),
    });
    setShareLogId(shareLogId);
    const shareTimelineContent = {
      query: setWxShareTimelineQuery(routeQuery),
      title: '资源汇聚，共创价值！',
      imageUrl: 'https://hb-saas.obs.cn-south-1.myhuaweicloud.com/mall/saas/gx_bg.png',
    };
    setShareTimelineContent(shareTimelineContent);
  }

  const params = reactive<ISupplyDemandSquareData>({
    cooperationTypeIdList: [],
    industryCategoryIdList: [],
    assType: null,
    current: 1,
    size: 10,
    boTypes: null,
    keyWord: '',
  });
  const dataList = ref<ISupplyDemandSquareResult[]>([]);

  provide('api', supplyDemandSquareList);
  const [register, { refresh }] = useConList();

  function searchFnc(keyword: string) {
    params.keyWord = keyword;
    refresh && refresh();
  }

  function handleFilterControlChange(e: {
    cooperationType: number[] | null;
    assTypeList: AssTypeEnum[] | null;
    industryIds: string[];
    boTypes: BoTypeEnum | null;
  }) {
    params.assTypeList = e.assTypeList;
    params.cooperationTypeIdList = e.cooperationType || [];
    params.industryCategoryIdList = e.industryIds;
    params.boTypes = e.boTypes;
    refresh && refresh();
  }

  onShow(() => {
    if (dataList.value.length) refresh?.();
  });

  /** 去我的供需 */
  async function handleCreate() {
    let isRead = false;
    if (enterOptions.value?.scene !== SceneValuesEnum.TIMELINE_SINGLEPAGE) {
      isRead = await getTypePublicity({ type: BusinessFunctionTypeEnum.BO });
    }
    if (isRead) {
      navigateTo({
        name: 'releaseBusinessOpportunities',
        options: {
          releaseType: ReleaseTypeEnum.member,
        },
      });
    } else {
      navigateTo({
        name: 'boPromotionalPage',
        options: {
          type: 'Square',
        },
      });
    }
  }

  onPageScroll(() => {});
  onShareAppMessage(() => ({}));
  onShareTimeline(() => ({}));
</script>
<style scoped lang="scss">
  .add-topic {
    position: fixed;
    right: 32rpx;
    bottom: 340rpx;
    width: 104rpx;
    height: 104rpx;
    border-radius: 50%;
    background: linear-gradient(0deg, #2878ff 0%, #7bacff 100%);
    box-shadow: 0px 4rpx 24rpx 0px rgba(150, 151, 153, 0.16);
    color: #fff;
    font-size: 24rpx;
    z-index: 99;
  }
</style>
